#!/bin/env python
#-*- coding:utf-8 -*-

#----------------------------------------------------------------------------
# Name     :      start.py
# Purpose  :      gui starter, include app module and splash code.
# Author   :      Albert cheng
# Created  :      2012-10-29
# Copyright:     (c) 2012 by Albertcheng
# Licence  :      wxWindows license
#----------------------------------------------------------------------------


import wx
from dbo import *
from gui_grid import *
from request_handler import request_xml
from log import Log



class DataConfigDialog(wx.Dialog):
    
    def __init__(self,proj,title,fn,type,md,tb,db,p_id,Tags,chd,dbh): 
        
        #title -- dialog's header text
        # fn   -- xml's argus
        # tag  -- xml's argus       
        # md   -- mysql's data
        # sd   -- sqls' data
        # tb   -- tb name
        # db   -- used database name
        # p_id -- player id
        # Tags -- gui's tag names
        self.type = type
        self.proj = proj
        self.log = Log()
        self.getxml = request_xml(self.log) 
        config = self.getxml.getxml(fn)#proj,fn,tag)
        self.player_id = p_id
        self.db = db
        self.player = md
        self.cfg = []
        self.dbh = dbh
        self.tb = tb
        #Tags = ["是否生成","道具名","道具数量"]
        if self.proj == "douhun":
            self.role = self.player["k_player_fightmsg"]["row_1"]["role"]
            if str(self.role) == "1":
                self.roletype = "saber"
            elif str(self.role) == "2":
                self.roletype = "caster"
        
        s_idx = []
        isbool = 0
        for k in sorted([int(x) for x in config.keys()]):
            att = config[k].attrib
            if self.proj == "douhun":
                if config[k].tag == "skill" and self.roletype in att["class"] and int(att["level"]) != 0:
                    s_idx.append(str(att["id"]))
                    if int(int(att["nextLevelId"])) == 0:
                        self.cfg.append([isbool,att["name"],",".join(s_idx),"",att["type"],att["group"]])
                        s_idx = []
                elif config[k].tag == "prop":
                    self.cfg.append([isbool,att["name"],int(att["id"]),""])
            elif self.proj == "ssdz":
                self.cfg.append([isbool,att["name"],int(att["id"]),""])
        
        
        wx.Dialog.__init__(self, None, -1, title, style=wx.CAPTION|wx.CLOSE_BOX)
        about   = wx.StaticText(self, -1, "欢迎使用离子战锤工作室的mysql工具.\n修改方法：\n1. 双击要修改道具、技能、武器所在行对应的等级/数量的空格\n2. 打开下拉框选择数据，然后点确认即可）".decode("utf-8"))

        sizer = wx.BoxSizer(wx.VERTICAL)
        
        
        self.griddata = [[x[0],x[1],x[2],'0'] for x in self.cfg]
        
        self.g = self.__make_grid_code(Tags,self.griddata,chd)
        
        self.g.SetMinSize((350,400))
        

        confirm = wx.Button(self,-1,"确认提交".decode("utf-8"))
        


        self.Bind(wx.EVT_BUTTON,self.OnConfirm,confirm)

        sizer.Add(about,0,wx.EXPAND,5)
        sizer.Add(wx.StaticLine(self,-1,size=(100,1)),0,wx.EXPAND,5)
        sizer.Add(self.g,0,wx.EXPAND,5)
        sizer.Add(confirm,0,wx.EXPAND|wx.ALIGN_CENTER,5)
        self.SetSizer(sizer)
        sizer.Fit(self)
        self.Centre()
        
        
        
        
        
    def __make_grid_code(self,Tags,data,chd):
        colsize = [(0,60),
                   (1,90),
                   (2,90),
                   (3,60)
                   ]
                
                
        dt = [
              GRID_BOOL,
              GRID_STRING,
              GRID_STRING,
              GRID_CHOICE+chd
              ]
        return CustTableGrid(self,Tags,dt,colsize,data)

    def OnConfirm(self,e):
        
        #=======================================================================
        # step 1: get data list from gui and mysql
        #=======================================================================
        sqls = []
        
        #=======================================================================
        # step 2: find out the repeat ids in mysql data and add the data into dellist
        #=======================================================================
        #prop_id_idx = 3# for project ssdz
        #prop_cnt_idx = 2
        dellist = []
        clear_id = {}
        #a = [x[3] for x in self.md]
        
        md = self.player[self.tb]
        nm = [x for x in md.keys()]
        nm.sort()
        
        
        for nd in nm:
            if self.type == "prop":
                data_key = [x for x in md[nd].keys() if x.lower() == "count"][0]
                item_id_key = [x for x in md[nd].keys() if "prop" in x.lower() and "id" in x.lower()][0]
            elif self.type == "skill":
                data_key = [x for x in md[nd].keys() if x.lower() == "level"][0]
                if self.proj == "douhun":
                    item_id_key = [x for x in md[nd].keys() if "group" in x.lower() and "id" in x.lower()][0]
                else:
                    item_id_key = [x for x in md[nd].keys() if "skill" in x.lower() and "id" in x.lower()][0]
                
            mysql_idx_key = [x for x in md[nd].keys() if x.lower() == "id"][0]
            player_id_key = [x for x in md[nd].keys() if "player" in x.lower() and "id" in x.lower()][0]
               
            item_id = int(md[nd][item_id_key])
            
            if item_id not in clear_id.keys():
                clear_id[int(item_id)] = md[nd]
            else:
                old_v = clear_id[int(item_id)][data_key]
                new_v = md[nd][data_key]
                if new_v > old_v:
                    dellist.append(clear_id[item_id][mysql_idx_key])
                    clear_id[int(item_id)] = md[nd]
                else:
                    dellist.append(md[nd][mysql_idx_key])
                    
        for n in dellist:
            sql =  "delete from %s.%s where %s='%s';" % (self.db,self.tb,mysql_idx_key,n)
            sqls.append(sql)
            
            
        
        #=======================================================================
        # step 3: check out if the data from gui is in the mysql data, if not ,insert it, otherwise, update it
        #=======================================================================
        
        for n in range(len(self.cfg)):
            self.cfg[n][0] = self.g.GetValue(n,0)
            cnt = self.g.GetValue(n,3)
            self.cfg[n][3] = cnt
        
        k = [int(x) for x in clear_id.keys()]
        try:
            g = [int(x["groupId"]) for x in clear_id.values()]
        except:
            g = []  
        
        for n_gui_d in self.cfg:
            isbool = n_gui_d[0]
            idx = n_gui_d[2]
            cnt = n_gui_d[3]
            if int(isbool) == 1:
                if self.type == "skill" and self.proj == "douhun":
                    ntype = n_gui_d[4]
                    group = n_gui_d[5]
                    
                    skill_keys = [int(x) for x in idx.split(",")]
                    if int(cnt) != 0:
                        t = int(cnt)-1
                    idx = skill_keys[t]
                    
                    if int(group) in g:
                        data_idx = ""
                        for k,v in clear_id.items():
                            if int(v["skillId"]) in skill_keys:
                                data_idx = v[mysql_idx_key]
                        
                        sql = "update %s.%s set %s='%s',`skillId`='%s' ,`groupId`='%s', `type`='%s' where %s='%s';" % (self.db,self.tb,data_key,cnt,idx,group,ntype,mysql_idx_key,data_idx)
                    else:
                        sql = "insert into %s.%s (`%s`,`skillId`,`%s`,`%s`,`groupId`,`type`) values(null,'%s','%s','%s','%s','%s')" % (\
                                                                                                       self.db,\
                                                                                                       self.tb,\
                                                                                                       mysql_idx_key,\
                                                                                                       data_key,\
                                                                                                       player_id_key,\
                                                                                                       idx,\
                                                                                                       cnt,\
                                                                                                       self.player_id,\
                                                                                                       group,\
                                                                                                       type)
                    
                    sqls.append(sql)
                else:
                       
                    if int(idx) in k:
                        data_idx = clear_id[int(idx)][mysql_idx_key]
                        sql = "update %s.%s set %s='%s' where %s='%s';" % (self.db,self.tb,data_key,cnt,mysql_idx_key,data_idx)
                        
                    else:
                        sql = "insert into %s.%s (`%s`,`%s`,`%s`,`%s`) values(null,'%s','%s','%s')" % (\
                                                                                                       self.db,\
                                                                                                       self.tb,\
                                                                                                       mysql_idx_key,\
                                                                                                       item_id_key,\
                                                                                                       data_key,\
                                                                                                       player_id_key,\
                                                                                                       idx,\
                                                                                                       cnt,\
                                                                                                       self.player_id)
                    sqls.append(sql)
        
        if sqls != []:
            for n in sqls:print n
            try:
                self.dbh.dosql(sqls)
                wx.MessageBox("数据修改成功！", "提示".decode("utf-8"), wx.OK)
                self.Destroy()
                
            except MySQLdb.Error,e:
                self.Log.log(e[1])
                wx.MessageBox("数据修改失败    -。-！！\n"+e[1], "提示".decode("utf-8"), wx.OK)
                self.Destroy()
            return
        else:
            wx.MessageBox("未提交任何改变。", "提示".decode("utf-8"), wx.OK)
            self.Destroy()            
